package com.qyhl.module_home.new_message;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.user.MessageUnreadBean;
import com.qyhl.webtv.commonlib.service.CircleService;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import q.rorbin.badgeview.QBadgeView;


/**
 * 新首页消息中心
 */
@Route(path = ARouterPathConstant.NEW_MESSAGE, extras = ARouterPathConstant.LOGIN_NEEDED)
public class MessageActivity extends BaseActivity implements MessageContract.MessageView {
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.system_msg_txt)
    TextView systemMsgTxt;
    @BindView(R2.id.tip_msg_txt)
    TextView tipMsgTxt;
    @BindView(R2.id.interaction_msg_txt)
    TextView interactionMsgTxt;

    /**
     * 圈子服务
     */
    @Autowired(name = ServicePathConstant.CIRCLE_SERVICE)
    public CircleService circleService;

    private Fragment currentFragment;

    private MessagePresenter mPresenter;

    QBadgeView systemView, tipView, interactionView;

    private String lastTipTime, lastSystemTime;

    private String userName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSupportActionBar(toolbar);

    }


    @Override
    protected int getContentView() {
        return R.layout.home_activity_message_new;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.fitsSystemWindows(true)
                .statusBarColor(R.color.global_base)
                .init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        initView();
    }

    @Override
    protected void setListener() {

    }


    private void initView() {
        mPresenter = new MessagePresenter(this);
        BusFactory.getBus().register(this);
        lastTipTime = SpfManager.getInstance(this).getString("last_tip_time", "0");
        lastSystemTime = SpfManager.getInstance(this).getString("last_system_time", "0");
        userName = CommonUtils.getInstance().getUserName();
        add(circleService.getChatMessageFragment(), R.id.fragment_layout, "chat");
        mPresenter.getUnreadMsgNum(lastSystemTime, lastTipTime, userName);
    }


    public void add(Fragment fragment, int id, String tag) {
        FragmentManager mFragmentManager = getSupportFragmentManager();
        FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
        Fragment tempFragment = mFragmentManager.findFragmentByTag(tag);
        if (tempFragment != null) {
            fragment = tempFragment;
        }
        if (fragment.isAdded()) {
            addOrShowFragment(mFragmentTransaction, fragment, id, tag);
        } else {
            if (currentFragment != null && currentFragment.isAdded()) {
                mFragmentTransaction.hide(currentFragment).add(id, fragment, tag).commit();
            } else {
                mFragmentTransaction.add(id, fragment, tag).commit();
            }
            currentFragment = fragment;
        }
    }

    /**
     * 添加或者显示 fragment
     *
     * @param fragment 碎片
     */
    private void addOrShowFragment(FragmentTransaction transaction, Fragment fragment, int id, String tag) {
        if (currentFragment == fragment){
            return;
        }
        if (!fragment.isAdded()) {
            transaction.hide(currentFragment).add(id, fragment, tag).commit();
        } else {
            transaction.hide(currentFragment).show(fragment).commit();
        }
        currentFragment.setUserVisibleHint(false);
        currentFragment = fragment;
        currentFragment.setUserVisibleHint(true);
    }


    @Override
    public void setUnreadBadge(MessageUnreadBean bean) {
        if (bean.getuSystem() > 0) {
            if (systemView == null) {
                systemView = new QBadgeView(this);
            }
            systemView.bindTarget(systemMsgTxt).setGravityOffset(28, 3, true).setBadgeNumber(bean.getuSystem());
        } else {
            if (systemView != null) {
                systemView.hide(false);
            }
        }

        if (bean.getuTips() > 0) {
            if (tipView == null) {
                tipView = new QBadgeView(this);
            }
            tipView.bindTarget(tipMsgTxt).setGravityOffset(28, 3, true).setBadgeNumber(bean.getuTips());
        } else {
            if (tipView != null) {
                tipView.hide(false);
            }
        }

        if (bean.getuInteractive() > 0) {
            if (interactionView == null) {
                interactionView = new QBadgeView(this);
            }
            interactionView.bindTarget(interactionMsgTxt).setGravityOffset(28, 3, true).setBadgeNumber(bean.getuInteractive());
        } else {
            if (interactionView != null) {
                interactionView.hide(false);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({R2.id.system_msg_txt, R2.id.tip_msg_txt, R2.id.interaction_msg_txt})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.system_msg_txt) {

            Bundle bundle = new Bundle();
            bundle.putString("type", "system");
            RouterManager.router(ARouterPathConstant.MESSAGE_DETAIL,bundle);


        } else if (i == R.id.tip_msg_txt) {
            Bundle bundle = new Bundle();
            bundle.putString("type", "tips");
            RouterManager.router(ARouterPathConstant.MESSAGE_DETAIL,bundle);

        } else if (i == R.id.interaction_msg_txt) {
            RouterManager.router(ARouterPathConstant.MESSAGE_INTERACTION);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.MessageRefresh event) {
        if (event != null) {
            switch (event.getType()) {
                case "system":
                    lastSystemTime = SpfManager.getInstance(this).getString("last_system_time", "0");
                    mPresenter.getUnreadMsgNum(lastSystemTime, lastTipTime, userName);
                    break;
                case "tip":
                    lastTipTime = SpfManager.getInstance(this).getString("last_tip_time", "0");
                    mPresenter.getUnreadMsgNum(lastSystemTime, lastTipTime, userName);
                    break;
                default:
                    mPresenter.getUnreadMsgNum(lastSystemTime, lastTipTime, userName);
                    break;
            }
        }
    }
}
